import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'ngx-form-object',
  templateUrl: './form-object.component.html',
  styleUrls: ['./form-object.component.scss'],
})
export class FormObjectComponent implements OnChanges {
  @Input('fg') fg: any;
  protected readonly Object = Object;
  fieldName = '';
  keys: any[] = [];

  constructor(
      private fb: FormBuilder,
  ) {
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['fg']) {
      this.fg = changes['fg'].currentValue;
      this.initData();
    }
  }

  initData() {
    this.keys = Object.keys(this.fg.controls).map(key => {
      let control = this.fg.controls[key];
      return {
        key, control,
        type: control instanceof FormArray ? 'array' :
            control instanceof FormGroup ? 'group' :
                'value',
      };
    });
  }

  /**添加字段*/
  addField(checked: boolean) {
    let control;
    if (checked) {
      control = this.fb.control(null, [Validators.required]);
      this.fg.addControl(this.fieldName, control);
    } else {
      control = this.fb.control(null, []);
    }
    this.fg.addControl(this.fieldName, control);
    this.keys.push({key: this.fieldName, control: control, type: 'value'});
    this.fieldName = '';
  }

  /**添加对象字段*/
  addObjectField() {
    let control = this.fb.group({});
    this.fg.addControl(this.fieldName, control);
    this.keys.push({key: this.fieldName, control: control, type: 'group'});
    this.fieldName = '';
  }

  /**添加数组字段*/
  addArrayField() {
    let control = this.fb.array([]);
    this.fg.addControl(this.fieldName, control);
    this.keys.push({key: this.fieldName, control: control, type: 'array'});
    this.fieldName = '';
  }

  /**校验字段是否可以添加*/
  get btnDisable() {
    if (!this.fieldName || this.fieldName.trim().length === 0) return true;
    return this.keys.indexOf(this.fieldName) !== -1;
  }

  /**删除字段*/
  removeField(key: string) {
    this.fg.removeControl(key);
    let idx = this.keys.findIndex(s => s.key === key);
    this.keys.splice(idx, 1);
  }
}
